package com.mzba.place.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.ReportListAdapter;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportInfoGson;
import com.mzba.place.ui.widget.CustomListView;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageLoader;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 
 * @author 06peng
 *
 */
public class MyReportListActivity extends BasicActivity implements Callback {

	private CustomListView listView;
	private List<ReportEntity> reports;
	private ReportEntity entry;
	private ReportListAdapter reportListAdapter;
	private ImageLoader mImageLoader;
	private double localLat;
	private double localLon;
	public PlaceApplication app;
	public LocationClient mLocClient;
	private Handler handler;
	/**
	 * 上报类型，0：我上报的；1：我赞过的；2：我收藏的;3:我评论的
	 */
	private int type;
	
	private final int init_reports = 1;
	private final int delete_report = 2;
	
	private final int menu_delete = 3;
	
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.fragment_report_list);
		actionBar.show();
		type = getIntent().getIntExtra("type", 0);
		actionBar.setDisplayShowTitleEnabled(true);
		if (type == 0) {
			setTitle("我上报的");
		} else if (type == 1) {
			setTitle("我赞过的");
		} else if (type == 2){
			setTitle("我支持的");
		} else if (type == 3) {
			setTitle("我评论的");
		}
		app = (PlaceApplication) getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        app.getMyListener().setHander(handler);
        mLocClient = app.mLocationClient;
		mImageLoader = ImageLoader.getInstance(this);
		
		listView = (CustomListView) findViewById(R.id.list_report);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent intent = new Intent();
				intent.setClass(MyReportListActivity.this, ReportDetailActivity.class);
				intent.putExtra("report_detail", reportListAdapter.getReportList().get(arg2-1));
				startActivity(intent);
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (type != 0 || type != 3) {
					if (reports != null && !reports.isEmpty()) {
						entry = reports.get(arg2 - 1);
						startActionMode(new AnActionModeOfNewsProportions());
					}
				}
				return true;
			}
		});
		menuMyPosition();
		UICore.eventTask(this, this, init_reports, null, true);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return false;
	}
	
	OnScrollListener onScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				mImageLoader.lock();
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				mImageLoader.unlock();
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				mImageLoader.lock();
				break;
			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			
		}
	};
	
	/**
	 * locate to my position
	 */
	public void menuMyPosition() {
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			
		option.setCoorType("bd09ll");		
		option.setAddrType("all");	
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);      
		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}
	
	public void execute(int mes, Object obj) {
		try {
			String response = null;
			switch (mes) {
			case init_reports:
				String url = null;
				if (type == 0) {
					url = UrlConfig.my_reports;
				} else if (type == 1) {
					url = UrlConfig.vote_reports;
				} else if (type == 2){
					url = UrlConfig.star_reports;
				} else if (type == 3) {
					url = UrlConfig.my_comments;
				}
				url += "?auth_token=" + AppContext.getInstance().getAuthToken();
				response = HttpUtils.doGet(url);
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					ReportInfoGson reportGson = gson.fromJson(response, ReportInfoGson.class);
					if (reportGson != null) {
						reports = reportGson.getReports();
					}
				}
				handler.sendEmptyMessage(init_reports);
				break;
			case delete_report:
				String deleteUrl = null;
				if (type == 1) {
					deleteUrl = UrlConfig.un_vote(entry.getId() + "");
				} else if (type == 2) {
					deleteUrl = UrlConfig.un_star(entry.getId() + "");
				}
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
				response = HttpUtils.doPost(this, deleteUrl, paramsMap);
				if (getRc(response) == 0) {
					handler.sendEmptyMessage(delete_report);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	};

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_reports:
			if (reports != null && !reports.isEmpty()) {
				reportListAdapter = new ReportListAdapter(this, reports, localLat, localLon, mImageLoader);
				listView.setAdapter(reportListAdapter);
			} else {
				List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("value", "暂无数据");
				SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.empty_listitem, 
						new String[] {"value"}, new int[] {R.id.value});
				listView.setAdapter(adapter);
			}
			break;
		case AppContext.LOCATE:
			localLat = app.latitude;
			localLon = app.longitude;
			break;
		case delete_report:
			try {
				reports.remove(entry);
				if (reports != null && !reports.isEmpty()) {
					reportListAdapter.notifyDataSetChanged();
				} else {
					List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("value", "暂无数据");
					SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.empty_listitem, 
							new String[] {"value"}, new int[] {R.id.value});
					listView.setAdapter(adapter);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		return false;
	}
	
	private int getRc(String json) {
		JSONObject jsonObject;
		int rc = 1;
		try {
			jsonObject = new JSONObject(json);
			rc = jsonObject.getInt("rc");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return rc;
	}
	
	private final class AnActionModeOfNewsProportions implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        	menu.add(0, menu_delete, 0, "删除").setIcon(R.drawable.icon_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
			case menu_delete:
				mode.finish();
				UICore.eventTask(MyReportListActivity.this, MyReportListActivity.this, delete_report, null, true);
				break;

			default:
				break;
			}
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
        	
        }
    }

}
